var G_windowTitle;
var form;
var dropdown;
var G_id;
var table;
var mytransfer;
var tb1;
var map;
var marker;
var lnglat = [];
var infoWindow = null;
$(document).ready(function () {
  initLayui();
  initTable();
  
  layui
    .config({
      base: 'layui_exts/transfer/',
    })
    .use('transferTable', function () {
      (mytransfer = layui.transferTable), ($ = layui.$);
    });
});

function initLayui() {
  layui.use(function () {
    form = layui.form;
    dropdown = layui.dropdown;
    table = layui.table;

    form.on('submit(filter)', function (data) {
      initTable();
      return false;
    });

    form.on('submit(search)', function (data) {
      initTable();
      return false;
    });

    form.on('submit(save)', function (data) {
      if (data.field.type != '1' && data.field.channelNo == '') {
        layer.msg('通道号不能为空！');
      } else if (data.field.type == '3' && data.field.macAddress == '') {
        layer.msg('mac地址不能为空！');
      } else {
        var params = {
          id: G_windowTitle == '新增' ? null : G_id,
          name: data.field.name,
          code: data.field.code,
          type: data.field.type,
          simId: data.field.simId,
          linkMan: data.field.linkMan,
          linkPhone: data.field.linkPhone,
          longitude: data.field.lnglat.split(',')[0],
          latitude: data.field.lnglat.split(',')[1],
          channelNo: data.field.type == '1' ? '' : data.field.channelNo,
          macAddress: data.field.macAddress,
        };
        save(params);
      }
      return false;
    });

    form.on('switch(updateStatus)', function (data) {
      AjaxRequest(
        '/user/status/update',
        callBack,
        {
          id: data.value,
          type: data.elem.checked ? 1 : 2,
        },
        'post'
      );

      function callBack(result) {
        if (result.status == 200) {
          layer.msg('已成功' + (data.elem.checked ? '启用！' : '停用！'));
        }
      }
    });

    form.on('submit(saveNotice)', function (data) {
      AjaxRequest(
        '/device/notice/save',
        callBack,
        {
          id: G_id,
          notifySms: data.field.notifySms,
          notifyVms: data.field.notifyVms,
          linkMan: data.field.linkMan,
          linkPhone: data.field.linkPhone,
        },
        'post'
      );

      function callBack(result) {
        if (result.status == 200) {
          initTable();
          layer.closeAll();
          layer.msg('保存成功！');
        }
      }
      return false;
    });

    form.on('submit(saveConfig)', function (data) {
      AjaxRequest(
        '/device/water/config/save',
        callBack,
        {
          deviceId: G_id,
          ntuConfig: data.field.ntuConfig,
        },
        'post'
      );

      function callBack(result) {
        if (result.status == 200) {
          layer.closeAll();
          layer.msg('保存成功！');
        }
      }
      return false;
    });

    form.on('submit(search-unbind)', function (data) {
      initTransfer(G_id);
      return false;
    });

    form.on('submit(saveLngLat)', function (data) {
      $('#lnglat').val(lnglat[0] + ',' + lnglat[1]);
      layer.close(layer.index);
      return false;
    });
  });
}

// 新增编辑弹窗
function showWindow(title, res) {
  layer.open({
    type: 1,
    title: title,
    skin: 'default-class',
    area: ['4.5rem', 'auto'],
    // shade: false,
    move: false,
    closeBtn: 2,
    id: 1, //设置该值后，不管是什么类型的层，都只允许同时弹出一个。
    content: `<form class="layui-form" lay-filter="saveForm" style="margin: .3rem;">
                <div class="layui-form-item">
                  <label class="layui-form-label">名称</label>
                  <div class="layui-input-block">
                    <input type="text" name="name" autocomplete="off" class="layui-input" lay-verify="required">
                  </div>
                </div>
                <div class="layui-form-item">
                  <label class="layui-form-label">设备号</label>
                  <div class="layui-input-block">
                    <input type="text" name="code" autocomplete="off" class="layui-input" lay-verify="required">
                  </div>
                </div>
                <div class="layui-form-item">
                  <label class="layui-form-label">类型</label>
                  <div class="layui-input-block">
                    <select id="type" name="type" lay-verify="required" lay-filter="type">
                      <option value="">请选择设备类型</option>
                      <option value="1">水质监测</option>
                      <option value="2">视频监控</option>
                      <option value="3">警戒球机</option>
                    </select>
                  </div>
                </div>
                <div class="layui-form-item">
                  <label class="layui-form-label">通道号</label>
                  <div class="layui-input-block">
                    <input type="text" name="channelNo" autocomplete="off" class="layui-input">
                  </div>
                </div>
                <div class="layui-form-item">
                  <label class="layui-form-label">mac地址</label>
                  <div class="layui-input-block">
                    <input type="text" name="macAddress" autocomplete="off" class="layui-input">
                  </div>
                </div>
                <div class="layui-form-item">
                  <label class="layui-form-label">经纬度</label>
                  <div class="layui-input-block">
                    <input type="text" name="lnglat" id="lnglat" readonly autocomplete="off" class="layui-input" lay-verify="required">
                    <i class="layui-icon layui-icon-location" onclick="showMapWindow()" style="position: absolute;bottom: .05rem;font-size: .28rem;right: .05rem;color: #fff;cursor: pointer;"></i>
                  </div>
                </div>
                <div class="layui-form-item">
                  <label class="layui-form-label">sim卡号</label>
                  <div class="layui-input-block">
                    <input type="text" name="simId" autocomplete="off" class="layui-input">
                  </div>
                </div>
                <div class="layui-form-item">
                  <label class="layui-form-label">联系人</label>
                  <div class="layui-input-block">
                    <input type="text" name="linkMan" autocomplete="off" class="layui-input">
                  </div>
                </div>
                <div class="layui-form-item">
                  <label class="layui-form-label">联系电话</label>
                  <div class="layui-input-block">
                    <input type="text" name="linkPhone" autocomplete="off" class="layui-input">
                  </div>
                </div>
                <div class="layui-form-item form-btn" style="text-align:center">
                  <div class="layui-input-block" style="margin-left: 0;">
                    <button class="layui-btn" lay-submit lay-filter="save">保存</button>
                  </div>
                </div>
              </form>`, //这里content是一个普通的String
    success: function (layero, index) {
      G_windowTitle = title;
      form.render();
      if (title == '编辑') {
        G_id = res.id;
        //给表单赋值
        form.val('saveForm', {
          name: res.name,
          code: res.code,
          type: res.type,
          simId: res.simId,
          linkMan: res.linkMan,
          linkPhone: res.linkPhone,
          lnglat: res.longitude + ',' + res.latitude,
          channelNo: res.channelNo,
          macAddress: res.macAddress,
        });
      }
    },
  });
}

function showMapWindow() {
  layer.open({
    type: 1,
    title: '经纬度',
    skin: 'default-class',
    area: ['14rem', '9rem'],
    // shade: false,
    move: false,
    closeBtn: 2,
    // id: 1, //设置该值后，不管是什么类型的层，都只允许同时弹出一个。
    content: `<div class="" style="margin: .2rem;height:calc(100% - .5rem)">
                <input type="text" required="" placeholder="地址查询" class="layui-input poi-input"
                                        id="tipinput">
                <div style="width:100%;height:calc(100% - .4rem)" id="map"></div>
                <div style="text-align:center;margin-top:.1rem">
                  <button class="layui-btn" lay-submit lay-filter="saveLngLat">保存</button>
                </div>
              </div>`, //这里content是一个普通的String
    success: function (layero, index) {
      map = new AMap.Map('map', {
        center: [101.497147, 36.643514],
        zoom: 9.8,
        mapStyle: 'amap://styles/grey',
      });

      AMapUI.loadUI(['misc/PoiPicker'], function (PoiPicker) {
        var poiPicker = new PoiPicker({
          input: 'tipinput',
          city: '西宁市', //城市
        });

        //初始化poiPicker
        poiPickerReady(poiPicker);
      });
      function poiPickerReady(poiPicker) {
        window.poiPicker = poiPicker;

        marker = new AMap.Marker();

        // infoWindow = new AMap.InfoWindow({
        //   offset: new AMap.Pixel(0, -20),
        // });

        //选取了某个POI
        poiPicker.on('poiPicked', function (poiResult) {
          var source = poiResult.source,
            poi = poiResult.item,
            info = {
              source: source,
              id: poi.id,
              name: poi.name,
              location: poi.location.toString(),
              address: poi.address,
            };

          marker.setMap(map);
          // map.setFitView();
          // infoWindow.setMap(map);

          marker.setPosition(poi.location);
          // infoWindow.setPosition(poi.location);

          const lData = {
            名称: info.name,
            地址: info.address,
            坐标: info.location,
          };
          lnglat = [poi.location.lng, poi.location.lat];
          // infoWindow.setContent(
          //   '位置信息: <pre>' + JSON.stringify(lData, null, 2) + '</pre>'
          // );
          // infoWindow.open(map, marker.getPosition());

          map.setCenter(marker.getPosition());
        });
      }
      ajax('../static/json/湟中区.json', function (err, geoJSON) {
        if (!err) {
          var geojson = new AMap.GeoJSON({
            geoJSON: geoJSON,
            // 还可以自定义getMarker和getPolyline
            getPolygon: function (geojson, lnglats) {
              // 计算面积
              var area = AMap.GeometryUtil.ringArea(lnglats[0]);

              return new AMap.Polygon({
                path: lnglats,
                fillOpacity: 0.1, // 面积越大透明度越高
                strokeColor: '#65D0E0',
                fillColor: '#2FC7FF',
              });
            },
          });
          map.add(geojson);
          geojson.on('click', function (event) {
            lnglat = [event.lnglat.lng, event.lnglat.lat];
            if (!marker) {
              addMarker(event.lnglat.lng, event.lnglat.lat);
            } else {
              map.remove(marker);
              addMarker(event.lnglat.lng, event.lnglat.lat);
            }
          });
          // map.setFitView();
          log.success('GeoJSON 数据加载完成');
        } else {
          log.error('GeoJSON 服务请求失败');
        }
      });

      map.on('click', function (event) {
        lnglat = [event.lnglat.lng, event.lnglat.lat];
        if (!marker) {
          addMarker(event.lnglat.lng, event.lnglat.lat);
        } else {
          map.remove(marker);
          addMarker(event.lnglat.lng, event.lnglat.lat);
        }
      });
    },
  });
}

function addMarker(lng, lat) {
  marker = new AMap.Marker({
    position: [lng, lat],
  });
  marker.setMap(map);
}

// 保存表单
function save(data) {
  AjaxRequest('/device/save', callBack, data, 'post');

  function callBack(result) {
    if (result.status == 200) {
      initTable();
      layer.closeAll();
      layer.msg('保存成功！');
    } else if (result.status == 400) {
      layer.msg(result.result);
    } else {
      layer.msg('保存失败！');
    }
  }
}

function initTable() {
  layui.use('table', function () {
    var table = layui.table;
    var height = $('.search-content').innerHeight() - 20;

    //第一个实例
    table.render({
      title: '',
      height: height,
      text: {
        none: '暂无数据',
      },
      elem: '#table',
      skin: 'nob',
      headers: {
        SessionId: JSON.parse(localStorage.getItem('userInfo')).sessionId,
      },
      url: ajaxPrefix() + '/device/list',
      where: {
        name: $('#search-name').val(),
        code: $('#search-code').val(),
        type: $('#search-type').val(),
      },
      parseData: function (res) {
        //res 即为原始返回的数据
        return {
          code: res.status == 200 ? 0 : 1, //解析接口状态
          msg: res.message, //解析提示文本
          count: res.result?res.result.total:0, //解析数据长度
          data: res.result?res.result.data:[], //解析数据列表
        };
      },
      request: {
        pageName: 'pageNum', //页码的参数名称，默认：page
        limitName: 'pageSize', //每页数据量的参数名，默认：limit
      },
      page: {
        //开启分页
        limit: 10,
      },
      cols: [
        [
          //表头
          {
            field: 'name',
            title: '名称',
            align: 'center',
          },
          {
            field: 'code',
            title: '设备号',
            align: 'center',
          },
          {
            field: 'typeDesc',
            title: '类型',
            align: 'center',
          },
          {
            field: 'channelNo',
            title: '通道号',
            align: 'center',
          },
          {
            field: 'macAddress',
            title: 'mac地址',
            align: 'center',
          },
          {
            field: 'linkMan',
            title: '联系人',
            align: 'center',
          },
          {
            field: 'linkPhone',
            title: '联系电话',
            align: 'center',
          },
          {
            field: '',
            title: '操作',
            align: 'center',
            width: 250,
            templet: function (d) {
              let res = JSON.stringify(d);
              // onclick='showNoticeWindow(${res})'
              return `<div class="table-tool">
                        <div onclick='showWindow("编辑",${res})'>
                          <img src="../static/img/edit.png">编辑
                        </div>
                        <div>
                          <button id="id-${d.id}" class="layui-btn-xs layui-btn-primary layui-border-blue" style="color: #1DD4FF !important;border-color: #1DD4FF !important;cursor:pointer" onclick='initDropdown(${res})'>
                          更多
                          <i class="layui-icon layui-icon-down"></i>
                          </button>
                        </div>
                        <div onclick='showDelWindow(${res})'>
                          <img src="../static/img/delete.png">删除
                        </div>
                      </div>`;
            },
          },
        ],
      ],
    });
  });
}

function initDropdown(res) {
  var data = [
    {
      title: '设备原始报文',
      id: 'report',
    },
    {
      title: '告警通知设置',
      id: 'notice',
    },
    {
      title: '阈值设置',
      id: 'config',
    },
  ];
  if (res.type == 1) {
    data.push({
      title: '设备绑定',
      id: 'bind',
    });
  }
  //下拉菜单
  dropdown.render({
    elem: $('#id-' + res.id),
    show: true, //外部事件触发即显示
    data: data,
    click: function (menudata) {
      switch (menudata.id) {
        case 'report':
          showReportWindow(res);
          break;
        case 'notice':
          showNoticeWindow(res);
          break;
        case 'config':
          showConfigWindow(res);
          break;
        case 'bind':
          showBindWindow(res);
          break;
      }
    },
    align: 'right',
    style: 'box-shadow: 1px 1px 10px rgb(0 0 0 / 12%);', //设置额外样式
  });
}

function showBindWindow(res) {
  layer.open({
    type: 1,
    title: '设备绑定',
    skin: 'default-class',
    area: ['15rem', '8rem'],
    // shade: false,
    move: false,
    closeBtn: 2,
    id: 1, //设置该值后，不管是什么类型的层，都只允许同时弹出一个。
    content: `<div style="margin: .3rem;height: calc(100% - 0.6rem);">
                <div class="transfer-searchbar">
                  <div class="unbound-block">
                    <form class="layui-form">
                      <div class="layui-form-item">
                        <div class="layui-inline">
                          <label class="layui-form-label">未绑定设备</label>
                          <div class="layui-input-inline">
                            <input type="text" id="search-unbindName" autocomplete="off" class="layui-input" placeholder="请输入设备名称" >
                          </div>
                          <div class="layui-input-inline">
                            <button class="layui-btn" lay-submit lay-filter="search-unbind">查询</button>
                          </div>
                        </div>
                      </div>
                    </form>
                  </div>
                  <div class="bound-block">
                    <form class="layui-form">
                      <div class="layui-form-item">
                        <div class="layui-inline">
                          <label class="layui-form-label">已绑定设备</label>
                          <div class="layui-input-inline">
                            <input type="text" id="search-bindName" autocomplete="off" class="layui-input" placeholder="请输入设备名称" >
                          </div>
                          <div class="layui-input-inline">
                            <button class="layui-btn" lay-submit lay-filter="search-bind">查询</button>
                          </div>
                        </div>
                      </div>
                    </form>
                  </div>
                </div>
                <div id="transfer" style="height: calc(100% - 0.6rem);"></div>
              </div>`,
    success: function (layero, index) {
      G_id = res.id;
      initTransfer(res.id);
    },
  });
}

function initTransfer(deviceId) {
  AjaxRequest(
    '/device/link/info?deviceId=' +
      deviceId +
      '&types=' +
      [2] +
      '&boundKey=' +
      $('#search-bindName').val() +
      '&unboundKey=' +
      $('#search-unbindName').val(),
    callBack
  );

  function callBack(result) {
    if (result.status == 200) {
      var cols = [
        {
          type: 'checkbox',
          fixed: 'left',
        },
        {
          field: 'deviceName',
          title: '设备名称',
        },
        {
          field: 'typeName',
          title: '设备类型',
        },
        {
          field: 'deviceCode',
          title: '设备号',
        },
      ];
      //表格配置文件
      var tabConfig = {
        page: true,
        limits: [10, 20, 50],
      };
      tb1 = mytransfer.render({
        elem: '#transfer',
        data: [result.result.unbound, result.result.bound],
        cols: cols,
        tabConfig: tabConfig,
      });
    }
  }
}

function bindNodes() {
  setTimeout(() => {
    let data = mytransfer.data[1].data;
    AjaxRequest(
      '/device/link/save',
      callBack,
      {
        deviceId: G_id,
        type: 1,
        link: data,
      },
      'post'
    );

    function callBack(result) {
      initTransfer(G_id);
    }
  });
}

function showConfigWindow(res) {
  layer.open({
    type: 1,
    title: '阈值设置',
    skin: 'default-class',
    area: ['4.5', 'auto'],
    // shade: false,
    move: false,
    closeBtn: 2,
    id: 1, //设置该值后，不管是什么类型的层，都只允许同时弹出一个。
    content: `<form class="layui-form" lay-filter="configForm" style="margin: .3rem;height: calc(100% - 0.6rem);">
                <div class="layui-form-item">
                  <label class="layui-form-label">浊度</label>
                  <div class="layui-input-block">
                    <input type="text" name="ntuConfig" autocomplete="off" class="layui-input" lay-verify="required|number">
                  </div>
                </div>
                <div class="layui-form-item form-btn" style="text-align:center">
                  <div class="layui-input-block" style="margin-left: 0;">
                    <button class="layui-btn" lay-submit lay-filter="saveConfig">保存</button>
                  </div>
                </div>
              </form>`, //这里content是一个普通的String
    success: function (layero, index) {
      G_id = res.id;
      AjaxRequest('/device/water/config/info?deviceId=' + res.id, callBack);

      function callBack(result) {
        if (result.status == 200 && result.result != null) {
          form.val('configForm', {
            ntuConfig: result.result.ntuConfig,
          });
        }
      }
    },
  });
}

function showReportWindow(res) {
  layer.open({
    type: 1,
    title: '历史报文',
    skin: 'default-class',
    area: ['15rem', '8rem'],
    // shade: false,
    move: false,
    closeBtn: 2,
    id: 1, //设置该值后，不管是什么类型的层，都只允许同时弹出一个。
    content: `<div class="report-table" style="margin: .3rem;height: calc(100% - 0.6rem);">
                <table id="report-table"></table>
              </div>`, //这里content是一个普通的String
    success: function (layero, index) {
      table.render({
        title: '',
        height: $('.report-table').innerHeight(),
        text: {
          none: '暂无数据',
        },
        elem: '#report-table',
        skin: 'nob',
        headers: {
          SessionId: JSON.parse(localStorage.getItem('userInfo')).sessionId,
        },
        url: ajaxPrefix() + '/device/report/list',
        where: {
          deviceId: res.id,
        },
        parseData: function (res) {
          //res 即为原始返回的数据
          return {
            code: res.status == 200 ? 0 : 1, //解析接口状态
            msg: res.message, //解析提示文本
            count: res.result?res.result.total:0, //解析数据长度
            data: res.result?res.result.data:[], //解析数据列表
          };
        },
        request: {
          pageName: 'pageNum', //页码的参数名称，默认：page
          limitName: 'pageSize', //每页数据量的参数名，默认：limit
        },
        page: {
          //开启分页
          limit: 10,
        },
        cols: [
          [
            //表头
            {
              field: 'dataTime',
              title: '时间',
              align: 'center',
              width: 180,
            },
            {
              field: 'content',
              title: '报文',
              align: 'center',
            },
          ],
        ],
      });
    },
  });
}

function showDelWindow(res) {
  layer.confirm(
    '确认是否删除?',
    {
      btn: ['确认', '取消'], //按钮
    },
    function () {
      AjaxRequest('/device/delete?id=' + res.id, callBack);

      function callBack(result) {
        if (result.status == 200) {
          initTable();
          layer.closeAll();
          layer.msg('删除成功!');
        }
      }
    }
  );
}

function showNoticeWindow(res) {
  layer.open({
    type: 1,
    title: '告警通知设置',
    skin: 'default-class',
    area: ['4.5rem', 'auto'],
    // shade: false,
    move: false,
    closeBtn: 2,
    id: 1, //设置该值后，不管是什么类型的层，都只允许同时弹出一个。
    content: `<form class="layui-form" lay-filter="saveForm" style="margin: .3rem;height:calc(100% - .6rem)">
                <div class="layui-form-item">
                  <label class="layui-form-label">短信通知</label>
                  <div class="layui-input-block">
                    <select name="notifySms" lay-verify="required">
                      <option value="">请选择</option>
                      <option value="1">是</option>
                      <option value="0">否</option>
                    </select>
                  </div>
                </div>
                <div class="layui-form-item">
                  <label class="layui-form-label">语音通知</label>
                  <div class="layui-input-block">
                    <select name="notifyVms" lay-verify="required">
                      <option value="">请选择</option>
                      <option value="1">是</option>
                      <option value="0">否</option>
                    </select>
                  </div>
                </div>
                <div class="layui-form-item">
                  <label class="layui-form-label">联系人</label>
                  <div class="layui-input-block">
                    <input type="text" name="linkMan" autocomplete="off" class="layui-input" lay-verify="required">
                  </div>
                </div>
                <div class="layui-form-item">
                  <label class="layui-form-label">联系电话</label>
                  <div class="layui-input-block">
                    <input type="text" name="linkPhone" autocomplete="off" class="layui-input" lay-verify="required|phone">
                  </div>
                </div>
                <div class="layui-form-item form-btn" style="text-align: center;">
                  <div class="layui-input-block" style="margin-left: 0;">
                    <button class="layui-btn" lay-submit lay-filter="saveNotice">保存</button>
                  </div>
                </div>
              </form>`, //这里content是一个普通的String
    success: function (layero, index) {
      form.render();
      G_id = res.id;
      //给表单赋值
      form.val('saveForm', {
        notifySms: res.notifySms,
        notifyVms: res.notifyVms,
        linkMan: res.linkMan,
        linkPhone: res.linkPhone,
      });
    },
  });
}
